                                          
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event, context) => {
  const db = cloud.database()
  const { keyword, page = 1, pageSize = 10 } = event
  const COLLECTION_LIMIT = page * pageSize // 动态 LIMIT 确保覆盖分页范围

  const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

  // 查询数据（带 LIMIT）
  const searchCollection = async (collectionName, fields) => {
    const escapedKeyword = escapeRegExp(keyword)
    const query = {
      $or: fields.map(field => ({
        [field]: db.RegExp({ regexp: escapedKeyword, options: 'i' })
      }))
    }
    try {
      return await db.collection(collectionName)
        .where(query)
        .limit(COLLECTION_LIMIT)
        .get()
        .then(res => res.data)
    } catch (err) {
      console.error(`${collectionName}查询失败:`, err)
      return []
    }
  }

  // 处理 VenuesList 的子项数据
  const processVenues = (venuesData, keyword) => {
    const escapedKeyword = escapeRegExp(keyword)
    const regex = new RegExp(escapedKeyword, 'i')
    return venuesData.flatMap(venue => {
      const matchedSub = venue.data.filter(sub => 
        regex.test(sub.className) || 
        regex.test(sub.address) || 
        regex.test(sub.introduction)
      )
      return matchedSub.map(sub => ({
        venueId: venue._id,
        venueName: venue.name,
        venuePic: venue.pic,
        ...sub,
        type: 'venue'
      }))
    })
  }

  // 获取总数（直接基于数据查询结果统计，确保准确性）
  const getTotalCount = async (collectionName, fields) => {
    try {
      const data = await searchCollection(collectionName, fields)
      return data.length
    } catch (err) {
      console.error(`${collectionName}总数统计失败:`, err)
      return 0
    }
  }

  // VenuesList 总数统计
  const getVenuesTotal = async () => {
    try {
      const venuesData = await searchCollection('Venues', ['data.className', 'data.address', 'data.introduction'])
      const venueItems = processVenues(venuesData, keyword)
      return venueItems.length
    } catch (err) {
      console.error('Venues总数统计失败:', err)
      return 0
    }
  }

  try {
    // 并行查询数据
    const [pois, ecology, venues,foods,storys] = await Promise.all([
      searchCollection('Pois', ['name', 'address', 'adname']),
      searchCollection('EcologyList', ['text', 'desc']),
      searchCollection('Venues', ['data.className', 'data.address', 'data.introduction']),
      searchCollection('FoodList', ['food_name', 'food_intro', 'places']),
      searchCollection('StoryList', ['title', 'detail']),
    ])

    // 处理 Venues 数据
    const venueItems = processVenues(venues, keyword)

    // 合并并排序
    const allResults = [
      ...pois.map(i => ({ ...i, type: 'poi' })),
      ...ecology.map(i => ({ ...i, type: 'ecology' })),
      ...venueItems,
      ...foods.map(i => ({ ...i, type: 'food' })),
      ...storys.map(i => ({ ...i, type: 'story' }))
    ].sort((a, b) => (b._updateTime || 0) - (a._updateTime || 0))

    // 并行统计总数
    const [poisTotal, ecologyTotal, venuesTotal,foodsTotal,storysTotal] = await Promise.all([
      getTotalCount('Pois', ['name', 'address', 'adname']),
      getTotalCount('EcologyList', ['text', 'desc']),
      getVenuesTotal(),
      getTotalCount('FoodList', ['food_name', 'food_intro', 'places']),
      getTotalCount('StoryList', ['title', 'detail']),
    ])

    const total = poisTotal + ecologyTotal + venuesTotal + foodsTotal+storysTotal

    // 分页处理（强制修正越界值）
    const start = Math.max(0, (page - 1) * pageSize)
    const end = start + pageSize
    const visibleData = allResults.slice(start, end)
    const hasMore = end < allResults.length

    return {
      total,
      data: visibleData,
      hasMore,
      visibleTotal: allResults.length
    }
  } catch (err) {
    console.error('全局错误:', err)
    return { errMsg: err.message, data: [], hasMore: false, total: 0 }
  }
}                                           